package dinner.web.libs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import dinner.web.eat.IO;

public class IOUtils {

	public static <T extends Serializable> List<T> read(File menu, Class<T> type) {
		if (menu.exists()) {
			List<T> items = new ArrayList<T>();
			ObjectInputStream reader = null;
			try {
				reader = new ObjectInputStream(new FileInputStream(menu));
				do {
					T line = type.cast(reader.readObject());
					if (line != null) {
						items.add(line);
					} else {
						break;
					}
				} while (true);
			} catch (IOException e) {
			} catch (ClassNotFoundException e) {
				Logger.getLogger(IO.class.getName()).log(Level.SEVERE, e.getMessage(), e);
			} catch (ClassCastException e) {
				Logger.getLogger(IO.class.getName()).log(Level.SEVERE, e.getMessage(), e);
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException ex) {
						Logger.getLogger(IO.class.getName()).log(Level.SEVERE, null, ex);
					}
				}
			}
			if (items.size() > 0)
				return items;
		}
		return null;
	}

	public static void write(List<? extends Serializable> eats, File path) {
		ObjectOutputStream reader = null;
		if (!path.getParentFile().exists()) {
			path.getParentFile().mkdirs();
		}
		if (path.exists()) {
			path.delete();
		}
		try {
			reader = new ObjectOutputStream(new FileOutputStream(path));
			for (Serializable item : eats) {
				reader.writeObject(item);
			}
	
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				// TODO: handle exception
			}
		}
	}

}
